package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.ApUserFollowService;
import com.heima.utils.thread.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUserFollowServiceImpl extends ServiceImpl<ApUserFollowMapper, ApUserFollow> implements ApUserFollowService {


    /**
     * 关注与取消关注
     * @param dto
     * @return
     */
    public ResponseResult follow(UserRelationDto dto){
        //检查参数
        if (dto.getArticleId()==null||dto.getOperation()==null||dto.getAuthorId()==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getOperation()<0||dto.getOperation()>1){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUserFollow userFollow=new ApUserFollow();
        userFollow.setUserId(UserThreadLocalUtil.getUser().getId());
        userFollow.setFollowId(dto.getAuthorId());
        userFollow.setCreatedTime(new Date());
        System.out.println("userFollow="+userFollow);

        if(dto.getOperation()==0){
            //关注

            //查询是否已关注
            if(isFollow(dto.getAuthorId(),UserThreadLocalUtil.getUser().getId())){
                //已关注，直接返回
                System.out.println("已关注了");
                return new ResponseResult<>();
            }

            boolean save = save(userFollow);
            if (!save){
                throw new CustomException(AppHttpCodeEnum.FAIL_TO_SAVE_FOLLOW);
            }
        }
        if (dto.getOperation()==1){
            //取消关注
            QueryWrapper<ApUserFollow> wrapper=new QueryWrapper<>();
            wrapper.eq("user_id",UserThreadLocalUtil.getUser().getId());
            wrapper.eq("follow_id",dto.getAuthorId());
            boolean remove = remove(wrapper);
            if (!remove){
                throw new CustomException(AppHttpCodeEnum.FAIL_TO_CANCEL_FOLLOW);
            }
        }

        return new ResponseResult<>();
    }

    /**
     * 查看是否已关注
     */
    public Boolean isFollow(Integer authorId,Integer userId){
        QueryWrapper<ApUserFollow> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("follow_id",authorId);
        ApUserFollow userFollow = getOne(wrapper);
        if (userFollow==null){
            return false;
        }
        return true;
    }
}
